﻿using System;
using Creventive.Wpf.ShellFactory.Services;
using Creventive.Wpf.ShellFactory.Workspace;
using MultiViewWithLogin.Shell.Login;
using MultiViewWithLogin.Shell.Login.RuntimeModels;

[assembly: ApplicationViewModel(typeof(LoginViewModel), typeof(ILoginViewModel))]

namespace MultiViewWithLogin.Shell.Login.RuntimeModels
{
    internal class LoginViewModel : ApplicationViewModel, ILoginViewModel
    {
        private ModelCommand<string[]> loginCommand;
        private LoginState loginState = LoginState.Ready;

        public LoginViewModel(IServiceContainer services)
            : base(services, ApplicationViewModelFlags.None)
        {
            this.loginCommand = new ModelCommand<string[]>(this.BeginLogin);
        }

        public event EventHandler Succeeded;

        public ICommand<string[]> LoginCommand
        {
            get { return this.loginCommand; }
        }

        public LoginState LoginState
        {
            get { return this.loginState; }
            private set
            {
                if (this.loginState == value)
                    return;
                this.loginState = value;
                if (this.loginState == LoginState.LoginSucceeded)
                {
                    var handler = this.Succeeded;
                    if (handler != null)
                        handler.Invoke(this, EventArgs.Empty);
                }
                this.OnLoginStateChanged();
            }
        }

        public void BeginLogin(string[] loginInformation)
        {
            this.LoginState = LoginState.LoggingIn;
            if (loginInformation == null || loginInformation.Length != 2)
                this.LoginState = LoginState.LoginFailed;
            else if (string.Equals(loginInformation[0], "user", StringComparison.CurrentCultureIgnoreCase) && string.Equals(loginInformation[1], "password", StringComparison.CurrentCulture))
                this.LoginState = LoginState.LoginSucceeded;
            else
                this.LoginState = LoginState.LoginFailed;
        }

        protected virtual void OnLoginStateChanged()
        {
            this.OnPropertyChanged("LoginState");
        }
    }
}